A r t i c l e s
Navigation

Note: This site is
a bit older, personal views
may have changed.

M a i n P a g e

D i r e c t o r y

Freepascal Sockets Connect To HTTP Server


On MS Windows the sockets.pp unit CONNECT() functions with sIn and sOut (text handles) do not appear to work. In the mean time, you can use the Send() and Recv() functions for simple cross platform sockets programming.

Update: that bug has been reported and found, for example see:

  • Temporary Fix: here
  • Bug reported: here

The below program uses the simple sockets unit and not Synapse or Indy. Sometimes you may want to get to the point and just use sockets without third party stuff such as synapse or indy. And you can do it..

In the below example I show how you can connect to your webserver that you have installed on localhost (127.0.0.1) using only the connect, send, and recv functions without any SIN and SOUT reliance.

HTTP servers are picky about line feeds! remember to send TWO line feeds after your GET request. Only one line feed will not work. The below program sends two line feeds by appending one to the GET string request, and another send separately.

program test; {$mode objfpc} {$h+}
 
uses 
  sockets;

Var
  sAddr : TInetSockAddr;
  S : Longint;
  dummy: boolean = false;
  closed: boolean;
  len: longint;
  i: longint;

// just a simple buffer 
const
   BufSize = 2048; 
var
   Buf : array[0..BufSize - 1] of Char;

procedure socksend(pc: pchar);
begin
  len:= send(s, pc[0], length(pc), 0);  
  writeln('debug: socksend: len: ', len);
  if len = -1 then writeln('send error');
end;

procedure sockrecv;
begin
  closed:= false;
  while not closed do
  begin
    writeln('debug: begin while');
    len:= sockets.recv(S, Buf, sizeof(Buf), 0);
    writeln('recv buf len: ', len);
    if Len = 0 then 
    begin
      writeln('closed');
      Closed := True ;
    end else 
      for i := 0 to Len - 1 do Write(Buf[i]);
    writeln;
    writeln('debug: end while');
  end;
end;

var
  getreq: pchar = 'GET /index.htm HTTP/1.1'#13#10 +
                  'Accept: text/html'#13#10 +
                  'Connection: close'#13#10 +
                  'Host: localhost'#13#10 ;
  crlf: pchar = ''#13#10;
begin

  sAddr.sin_family:=AF_INET;
  { port 80 in network order }
  sAddr.sin_port:=80 shl 8;
  // Below SHL code is ugly, use DNS lookup functions instead.
  // I kept it simple for this example.
  { localhost : 127.0.0.1 in network order }
  sAddr.sin_addr.s_addr:=((1 shl 24) or 127); 
  S:= Socket(AF_INET, SOCK_STREAM, 0);
  if S = -1 then writeln('Socket errror ');
  writeln('debug: S: ', S);
  if not Connect(S, sAddr, sizeof(sAddr)) then writeln('Connect error');

  socksend(getreq);
  socksend(crlf);
  sockrecv;
end.



About
This site is about programming and other things.
_ _ _